package cn.itcast.bos.action.base;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.apache.commons.lang.StringUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.ICourierService;
import cn.itcast.bos.service.base.IStandardService;

/**
 * 快递员
 * @author hds
 *
 */
@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier>{

	private static final long serialVersionUID = -2418698772492022659L;
	
	private Courier courier = new Courier();
	
	private int page;	// 当前页
	private int rows;	// 每页显示数据条数
	private String ids;
	
	public void setIds(String ids) {
		this.ids = ids;
	}

	@Override
	public Courier getModel() {
		return courier;
	}
	
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	@Autowired
	private ICourierService courierService;
	@Autowired
	private IStandardService standardService;
	
	/**
	 * 添加快递员
	 * @return
	 */
	@Action(value="courier_save",results={@Result(name="success",location="/pages/base/courier.html",type="redirect")})
	public String courierSave(){
		courierService.save(courier);
		return SUCCESS;
	}
	
	/**
	 * 收派标准
	 * @return
	 */
	@Action(value="standard_query",results={@Result(name="success",type="json")})
	public String courierQuery(){
		List<Standard> standards = standardService.findAll();
		ActionContext.getContext().getValueStack().push(standards);
		return SUCCESS;
	}
	
	// 分页条件查询
	@Action(value="courier_page_Query",results={@Result(name="none",type="json")})
	public String courierPageQuery(){
		// 封装pageable
		Pageable pageable = new PageRequest(page-1,rows);
		Specification<Courier> specification = new Specification<Courier>() {
			// root：根对象，保存泛型中所有属性
			// criteriaQuery：构建简单查询条件
			// criteriaBuilder：构建复杂查询条件
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				ArrayList<Predicate> arrayList = new ArrayList<>();
				// 构建工号查询条件,类似courierNum = ?
				// isNotBlank:不为null
				if(StringUtils.isNotBlank(courier.getCourierNum())){
					Predicate courierNumWhere = cb.equal(root.get("courierNum").as(Integer.class),courier.getCourierNum());
					arrayList.add(courierNumWhere);
				}
				// 构建所属单位查询条件
				if(StringUtils.isNotBlank(courier.getCompany())){
					Predicate courierCompanyWhere = cb.like(root.get("company").as(String.class), "%"+courier.getCompany()+"%");
					arrayList.add(courierCompanyWhere);
				}
				// 构建类型查询条件
				if (StringUtils.isNotBlank(courier.getType())) {
					Predicate courierTypeWhere = cb.like(root.get("type").as(String.class), "%"+courier.getType()+"%");
					arrayList.add(courierTypeWhere);
				}
				// 构建收派标准查询，连接standard表
				// 内链接查询
				Join<Object, Object> standardRoot = root.join("standard",JoinType.INNER);
				if(courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())){
					Predicate courierStandardWhere = cb.like(standardRoot.get("name").as(String.class), "%"+courier.getStandard().getName()+"%");
					arrayList.add(courierStandardWhere);
				}
				return cb.and(arrayList.toArray(new Predicate[0]));
			}
		};
		Page<Courier> couriers = courierService.pageQuery(specification,pageable);
		// 组装数据
		Map<String, Object> map = new HashMap<>();
		map.put("total", couriers.getTotalElements());
		map.put("rows", couriers.getContent());
		// 将数据压入栈顶
		ActionContext.getContext().getValueStack().push(map);
		return NONE;
	}
	
	/**
	 * 批量作废
	 * @return
	 */
	@Action(value="batch_handle",results={@Result(name="none",type="redirect",location="/pages/base/courier.html")})
	public String delBatchHandle(){
		String[] idArr = ids.split(",");
		// 前台把操作拼接在id数组的最后一位
		String flag = idArr[idArr.length-1];
		// copyOfRange(要复制的数组，开始索引，结束索引)
		idArr = Arrays.copyOfRange(idArr, 0, idArr.length-1);
		Character deltag = null;
		if (StringUtils.equals("del", flag)) {
			deltag = '1';
		}
		courierService.batchHandle(deltag,idArr);
		return NONE;
	}
}
